package com.ruoyi.netty.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * Modbus TCP协议编码器
 */
@Slf4j
public class ModbusEncoder extends MessageToByteEncoder<ModbusMessage> {
    
    @Override
    protected void encode(ChannelHandlerContext ctx, ModbusMessage msg, ByteBuf out) throws Exception {
        // 写入MBAP头 (Modbus Application Protocol header)
        out.writeShort(msg.getTransactionId()); // 事务标识符
        out.writeShort(msg.getProtocolId());    // 协议标识符 (0 = Modbus)
        out.writeShort(msg.getLength());        // 后续数据的长度
        out.writeByte(msg.getUnitId());         // 单元标识符
        
        // 写入功能码
        out.writeByte(msg.getFunctionCode());
        
        // 写入数据部分
        if (msg.getData() != null && msg.getData().isReadable()) {
            out.writeBytes(msg.getData());
        }
        
        log.debug("Encoded Modbus message: transactionId={}, unitId={}, functionCode={}",
                msg.getTransactionId(), msg.getUnitId(), msg.getFunctionCode());
    }
} 